<?php
namespace Home\Controller;
use Common\Controller\HomebaseController;
use Home\Service\ClockTimeService;
// +----------------------------------------------------------------------
// | Date:2017年2月20日
// +----------------------------------------------------------------------
// | Author: EK_熊<1439527494@qq.com>
// +----------------------------------------------------------------------
// | Description: 此文件作用于****
// +----------------------------------------------------------------------
class ApplyController extends HomebaseController{
    
    protected $type = '';
    public function _initialize(){
        $this->model = D('Apply');
        $this->type = C('APPLY_TYPE');//申请类型
        $this->assign('title',$this->type[I('type')]);
    }
    
    
    
    /**
     * 列表
     * 
     * date:2017年2月20日
     * author: EK_熊
     */
    public function index(){
        $type = I('type'); 
        $page = I('page'); 
        $limit = I('limit',10); 

        
        if ($type == 2) $this->assign('vacate_type',C('VACATION_TYPE'));
        if ($type == 3) $this->assign('vacate_type',C('OT_TYPE'));
        $this->assign('status',['0'=>['审核中','waiting'],'1'=>['已通过','success'],'2'=>['拒绝','warn']]);
        $this->display();
    }
    
    /**
     * 申请记录列表，ajax输出，根据类型type 获取不同的申请数据（附带审核人信息）
     * 
     * date:2017年3月1日
     * author: EK_熊
     */
    public function showlist(){
        $type = I('type');
        $page = I('page');
        $limit = I('limit',10);
        $data['status'] = 0;
        $where['sn'] = $this->user_sn;
        $where['type'] = $type;
        $where['status'] = ['neq',3];
        $data['list'] = $this->model->where($where)->page($page,$limit)->order('id DESC')->getField('id,content,start_time,end_time,name,type,vacate_type,status,created_time');
        
        //获取行政审核员名字
        $opt_att = D('Options')->getOption('att_base',true);
        if ($data['list']) {
            $applyIdBox = array_keys($data['list']);
            $apprpover = D('Approver')->where(['apply_id'=>['in',$applyIdBox]])->field('*')->order('app_id DESC')->select();
            foreach ($data['list'] as $k=>$v) {
                for($i = 0; $i<count($apprpover);$i++){
                    if ($v['id'] == $apprpover[$i]['apply_id']){
                        //$apprpover[$i]['reject_reason']=$apprpover[$i]['reject_reason'] ? $apprpover[$i]['reject_reason'] :'无';
                        $data['list'][$k]['audit'][]=$apprpover[$i];
                    }
                    if ($data['list'][$k]['audit'][0]['approver_name'] == $opt_att['admin_name']) {
                       $data['list'][$k]['audit'] = array_reverse($data['list'][$k]['audit']);
                    }
                }
                $vcode = $v['vacate_type'] ? $v['vacate_type'] : $v['type'];

                $data['list'][$k]['type'] = get_vacation_name_ch($vcode);
               // $data['list'][$k]['content'] = $v['content'] ? $v['content'] : '无';
            }
            $data['status'] = 1;
        }

        $data['list'] = array_values($data['list']);
        $this->ajaxReturn($data);
    }
    
    /**
     * 取消申请
     * 
     * date:2017年3月27日
     * author: EK_熊
     */
    public function cancel(){
        $appid = I('id');
        $update_appro = M('Approver')->where(['apply_id'=>$appid])->setField('app_status',3);
        $update_apply = M('Apply')->where(['id'=>$appid])->setField('status',3);
        $this->success('操作完成');
    }
    

    /**
     * 提交申请
     *
     * date:2017年2月20日
     * author: EK_熊
     */
    public function submit(){
        $post = I('post');
        $type = I('type');
        
        $vacateTypeCfg = C('VACATION_TYPE');
        unset($vacateTypeCfg['118']);
        if ($type == 4) {
            //跳转至 补打卡页面
            $this->redirect('repair_submit');
        }
        
        $annualModel = D('AnnualLeave');
        if (IS_POST){
            $sickCode = ['104','109','110'];
            
            if (empty($post['content'])) $this->error('请填写申请理由！');
            //假期类型检查
            if (($post['type'] == 2 || $post['type']==1)&& empty($post['vacate_type'])) $this->error('请选择类型！');
            

            $current_day = date('Y-m-d',strtotime('-1 day'));//当天的日期开始时间

            //全部请假和外出，只能申请当天或者日后的时间
            if ($post['start_time'] < $current_day) $this->error('很抱歉,提交时间不允许');
            
            $timestamp_s = strtotime($post['start_time']);
            $timestamp_e = strtotime($post['end_time']);
            $day_s = date('Y-m-d',$timestamp_s);
            $day_e = date('Y-m-d',$timestamp_e);
            $year = date('Y',$timestamp_s);
            
            if ($post['vacate_type'] !== '200' && $post['type'] !== '3' && $post['start_time'] >= "$day_s 18:00") {
                $this->error('18:00是下班时间，不能作为开始时间！');
            }
            $type = $post['type'];
            $attDayModel = D('AttendanceDay');
            //加班数据检查
            if ($type == 3) {
                //工作日加班，凌晨通宵
                if ($post['vacate_type'] == 300) {
                    $cfg_work_day = C('ACTUAL_WORK_DAY');
                    $intrvalDay = date('d',$timestamp_e)-date('d',$timestamp_s);
                    
                    //不跨天的情况，1日期相同，2结束时间点小于配置的跨天时间点
                    if ($intrvalDay == 0 || $post['end_time'] <= "$day_e $cfg_work_day[1]") {
                        $this->error("该申请仅适用于晚上连续加班超过第二天凌晨6点");
                    }
                    $map_hav_att['date'] = date('Y-m-d',$timestamp_s);
                    $isHavAtt = $attDayModel->where($map_hav_att)->find();
                    if (!$isHavAtt) {
                        $this->error("当天没考勤数据，不允许提交申请！！");
                    }
                }
                //公休日加班
                if ($post['vacate_type'] == 301) {
                    if (is_work_day($day_s)) $this->error('开始日期必须是公休日~');

                    if (is_work_day($day_e)) {
                        if ($post['end_time'] > "$day_e 06:00:00") {
                            $this->error('结束日期必须是公休日~');
                        }
                    }
                }
                
            }
            
            if ($timestamp_s >= $timestamp_e) $this->error('请输入正确的起止时间！');
            
            /*时间区间覆盖问题的数据检查,检查开始时间 */
            $isExist_s = $this->model->where([
                'sn'=>$this->user_sn,
                "_string"=>"start_time <= '{$post['start_time']}' AND end_time >= '{$post['start_time']}'",
                'status'=>1
            ])->find();
            if ($isExist_s) $this->error('您可能重复提交了，请修改[开始时间]再提交吧~');
            
            /* 时间区间覆盖问题的数据检查,检查结束时间 */
            $isExist_e = $this->model->where([
                'sn'=>$this->user_sn,
                "_string"=>"start_time <= '{$post['end_time']}' AND end_time >= '{$post['end_time']}'",
                'status'=>1
            ])->find();

            if ($isExist_e) $this->error('您可能重复提交了，请修改[结束时间]再提交吧~');

            
            $clockTimeService = new ClockTimeService($post['start_time'],$post['end_time']);
            $vacation = $clockTimeService->get_intrval_work_time();

            if ($type == 2) {
                // 剔除连续时间内的非公日
                //适用于请假类型
                $unworkday = get_intrval_unwork_time($post['start_time'],$post['end_time']);
                if ($unworkday){
                    $vacation['total_min'] = $vacation['total_min']-$unworkday['total_min'];
                    $vacation['total_day'] = $vacation['total_day']-$unworkday['total_day'];
                    if ($vacation['total_min'] <=0 ) $this->error('您申请的日期可能是非工作日，请仔细检查后再提交~');
                }
            }
            

            
            //病假,年假，申请时间范围是当年的1月1日到12月31日
            if (in_array($post['vacate_type'],['109','110','103']) && ($post['start_time'] < "$year-01-01 00:00:00" || $post['end_time'] > "$year-12-31 23:59:59")){
                $this->error('很抱歉,日期不合法');
            }
            //婚假申请时长上限是3天
            if ($post['vacate_type'] == 105 && $vacation['total_day'] > 3){
                $this->error('很抱歉,婚假上限是3天');
            }
            
            
            if (in_array($post['vacate_type'],$sickCode)) {
                $remain = $annualModel->remain_sick($this->user_sn,$post['vacate_type']);
                $remainStr = time_day_8hour_zh($remain);
                
                if ($post['vacate_type'] == '109' && $vacation['total_min'] > $remain) {
                    $this->error("很抱歉，您只能申请{$remainStr}工时的全日薪病假！");
                }
                if ($post['vacate_type'] == '110' && $vacation['total_min'] > $remain) {
                    $this->error("很抱歉，您只能申请{$remainStr}工时的半日薪病假！");
                }
            }
            //短途类型
            if ($post['vacate_type'] == 200) {
                //不能超过24小时
                if ((strtotime($post['end_time'])-strtotime($post['start_time'])) > 86400) $this->error("短途外出不能超过24个小时");
                if (empty($post['resaon_img'])) $this->error("请提交相关证明!");
            }
            //长途类型
            if ($post['vacate_type'] == 201) {
                //必须大于24小时
                if ($vacation['total_day'] <= 1) $this->error("长途出差不能小于24个小时");
                if (empty($post['resaon_img'])) $this->error("请提交OA截图!");
            }
            //年假
            if ($post['vacate_type'] == 103) {
                if ($vacation['total_min'] > $this->attInfo['annual_min']) {
                    $this->error("很抱歉，您只能申请{$this->attInfo['annual']}年假！");
                }

            }
            //调休
            if ($post['vacate_type'] == 101) {
                if ($this->attInfo['overtime'] <= 0 ){
                    $this->error("很抱歉，您没有可以调休的时间！");
                }
                
                //查询截止至开始时间的可补休时间
                $remain_overtime = $attDayModel->count_remain_overtime($this->user_sn,'',$day_s);
 
                if($vacation['total_min'] > $remain_overtime) {
                    $timeAllow = time_day_8hour_zh($remain_overtime);
                    $this->error("很抱歉，截止{$day_s}为止,剩余可补休时间为{$timeAllow},调休时间不足！");
                }
                $unworkday = check_work_day($post['start_time'], $vacation['total_day']);
                if ($unworkday !== false){
                    $unworkdaystr = implode(',',$unworkday);
                    $this->error("很抱歉，您的申请包含非工作：{$unworkdaystr},请重新申请");
                }

            }
            
            //提交申请和审核数据的核心方法
            if ($post['resaon_img']) $post['resaon_img'] = $this->get_img_path($post['resaon_img']);
            $submitApply = $this->model->apply_submit($this->userInfo,$vacation,$post);
            
            if (!$submitApply){
                $this->error($this->model->getError());
                exit();
            }
            $this->ajaxReturn(['status'=>true,['info'=>'提交完成！']]);
            
            //$this->success('提交完成！',U('index',['type'=>$type]));
            exit();
        }
        if ($type == 2) {
            $sick_full_remain = $annualModel->remain_sick($this->user_sn,'109');
            $sick_half_remain = $annualModel->remain_sick($this->user_sn,'110');
            
            //全日薪，半日薪，最低薪，根据剩余量来单独显示
            if ($sick_full_remain <= 0) {
                unset($vacateTypeCfg['109']);
                if ($sick_half_remain <=0){
                    unset($vacateTypeCfg['110']);
                }else{
                    unset($vacateTypeCfg['104']);
                }
            }else{
                unset($vacateTypeCfg['110']);
                unset($vacateTypeCfg['104']);
            }
            $i = 0;
            foreach ($vacateTypeCfg as $k =>$v){
                $vacateType[$i]['title'] = $v;
                $vacateType[$i]['value'] = $k;
                $i++;
            }
            
            $this->assign('vacate_type_json',json_encode($vacateType));
        }
        
        if ($type == 1) $this->assign('vacate_type_json',json_encode(C('LEAVE_TYPE')));
        if ($type == 3) $this->assign('vacate_type_json',json_encode(C('OT_TYPE')));
        $this->assign('goback',U('index',['type'=>$type]));
        
            
        $this->display();
    }
    
    
    
    
    
    private function get_img_path($base64Box){
        if (empty($base64Box)) return '';
        
        for ($i=0;$i<count($base64Box);$i++){
            $path = base64ToImg($base64Box[$i], 'sick');
            if ($path) $ret[] = $path;
        }
        
        return $ret ? json_encode($ret) : false;
    }
    
    
    /**
     * 补办打卡申请，提交页面
     * 
     * date:2017年3月2日
     * author: EK_熊
     */
    public function repair_submit(){
        
        if (IS_POST) {
            $error = '';
            $repairtime = I('repair_time');
            $dutyType = I('duty_type');
            $repa_timestamp = strtotime($repairtime);
            $date = date('Y-m-d',$repa_timestamp);
            if (empty($repairtime)) $this->error('请选择正确的时间');
            if (empty($dutyType)) $this->error('请选择类型');
            
            //次数检查:每月每人只能申请3次
            $mon_start = date('Y-m-d');
            $mon_end = date('Y-m-d',strtotime("$mon_start +1 month -1 day"));
            $map_time['sn'] = $this->user_sn;
            $map_time['created_time'] = ['between',[$mon_start.' 00:00:00',$mon_end.' 23:59:59']];
            $map_time['type'] = 4;
            $map_time['status'] = ['in',[0,1]];
            $apply_time = M('Apply')->where($map_time)->count();//申请次数

            if (intval($apply_time) >= 3) {
                $this->error('很抱歉，每月补打卡次数不能超过3次!');
                exit();
            }
            /* 1.创建申请记录 */
            $attdayModel = D('AttendanceDay');
            
            $attDayInfo = $attdayModel->where(['sn'=>$this->user_sn,'date'=>$date])->field('UNIX_TIMESTAMP(duty_on) as duty_on,UNIX_TIMESTAMP(duty_off) as duty_off')->find();
            $duty_on = (int)$attDayInfo['duty_on'];
            $duty_off = (int)$attDayInfo['duty_off'];
            $this->model->startTrans();
            $add = [
                'sn'=>$this->userInfo['sn'],
                'name'=>$this->userInfo['name'],
                'uid'=>$this->user_uid,
                'total_min'=>0,
                'total_day'=>0,
                'dep_id'=>$this->userInfo['dep_id'],
                'dep_name'=>$this->userInfo['dep_name'],
                'created_time'=>CURRENT_TIME,
                'status'=>0,
                'type'=>4,
                'leader_uid'=>$this->userInfo['leader_id'],
            ];           
            do{
                if ($dutyType == '上班') $add['start_time'] = $repairtime;
                if ($dutyType == '下班') $add['end_time'] = $repairtime;

                $applyid = $this->model->add($add);
                if (!$applyid){
                    $error = '网络异常,操作失败！';
                    break;
                }
                /*添加申请人记录*/
                $appModel = D('Approver'); 
                $ret = $appModel->approver_repair($applyid,$this->userInfo);
                if (!$ret) {
                    $error = $appModel->getError();
                    break;
                }
                
            }while(false);
            
            
            if ($error) {
                $this->model->rollback();
                $this->error($error);
            }else{
                $this->model->commit();
                $this->success('提交成功！',U('index',['type'=>4]));
            }
        }
        $this->display();
    }
    
   
}